package wec_wallet.ebo.com.activity.options;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import bassproject.ebo.com.ebobass.activity.MyBassAppCompatActivity;
import bassproject.ebo.com.ebobass.http_utils.interfaces.IHttpPostListener;
import bassproject.ebo.com.ebobass.http_utils.utils.Ipost;
import bassproject.ebo.com.ebobass.utils.IToast;
import bassproject.ebo.com.ebobass.utils.I_Share;
import bassproject.ebo.com.ebobass.utils.Lg;
import bassproject.ebo.com.ebobass.utils.StringUtil;
import bassproject.ebo.com.model.GsonModel;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemClick;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.CSCustomServiceInfo;
import io.rong.imlib.model.UserInfo;
import wec_wallet.ebo.com.R;
import wec_wallet.ebo.com.utils.Functions;
import wec_wallet.ebo.com.utils.URLs;

public class ServiceActivity extends MyBassAppCompatActivity {

    @BindView(R.id.actionbar_back)
    RelativeLayout actionbar_back;
    @BindView(R.id.btn_contact)
    Button btn_contact;
    @BindView(R.id.lv_help)
    ListView lv_help;
    //客服电话
    String customer_service;
    String email_service;

    private List<Map<String, Object>> iData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service);
        ButterKnife.bind(this);
        initViews();
    }

    @Override
    public void initViews() {
        //发送协议
        Functions.post(this, URLs.HELP_LIST, null, new ListenerHelpList(), true, true);
    }

    @Override
    public void onClick(View v) {
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onClick_Back();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    //返回键
    @OnClick(R.id.actionbar_back)
    void onClick_Back() {
        finish();
    }

    @OnClick(R.id.btn_customservice)
    void toCustomServicePage() {
        if(true){
            IToast.show(getResources().getString(R.string.yet_open));
            return;
        }
        getRyInfo();
    }

    //联系方式
    @OnClick(R.id.btn_contact)
    void onClick_Call() {
        if(StringUtil.isEmpty(customer_service)||StringUtil.isEmpty(email_service)){
            return;
        }
        Intent intent = new Intent();
        intent.setClass(this,ServiceContactActivity.class);
        intent.putExtra("tel",customer_service);
        intent.putExtra("email",email_service);
        startActivity(intent);

    }

    @OnItemClick(R.id.lv_help)
    void clickHelp(int position) {
        Lg.d("clickHelp pos=" + position);
        Map<String, Object> postParams = new HashMap<String, Object>();
        postParams.put("id", iData.get(position).get("id"));
        Functions.post(this, URLs.HELP_DETAILS, postParams, new ListenerHelpDetails(), true, true);
    }

    private List<Map<String, Object>> buildData(JSONArray result) {
        Lg.d("buildData result=" + result.toString());
        List<Map<String, Object>> mydata = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = null;
        JSONObject jb = null;
        JSONObject jb_sub = null;
        String id = "";
        String title = "";
        for (int i = 0; i < result.length(); i++) {
            try {
                jb = new JSONObject(result.get(i).toString());
                Lg.d("jb " + i + " = " + jb.toString());
                id = jb.getString("id");
                title = jb.getString("title");
                map = new HashMap<String, Object>();
                map.put("id", id);
                map.put("title", title);
                mydata.add(map);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return mydata;
    }

    private void getRyInfo() {
        if (I_Share.isLogin()) {
            showLoading();
            Map<String, Object> postParams = new HashMap<>();
            postParams.put("token", I_Share.readAccountToken());
            postParams.put("uid", I_Share.readAccountUserid());
            Functions.post(this,URLs.GET_RY_INFO, postParams, new IHttpPostListener() {
                @Override
                public void onTimeOut() {
                    dismissLoading();
                }

                @Override
                public void responseSuccess(String result) {

                    if (!TextUtils.isEmpty(result)) {
                        Type type = new TypeToken<RY>() {
                        }.getType();
                        RY resp = gson.fromJson(result, type);
                        if (resp != null && "0".equalsIgnoreCase(resp.getError())) {
                            connect2RY(resp);
                        }
                    }

                }
            }, false, false);
        } else {
            finish();
        }
    }

    private void connect2RY(final RY model) {
        RongIM.connect(model.getToken(), new RongIMClient.ConnectCallback() {
            @Override
            public void onTokenIncorrect() {
                dismissLoading();
            }

            @Override
            public void onSuccess(String s) {
                //首先需要构造使用客服者的用户信息
                dismissLoading();
                CSCustomServiceInfo.Builder csBuilder = new CSCustomServiceInfo.Builder();
                CSCustomServiceInfo csInfo = csBuilder.nickName(model.getNickname()).portraitUrl(model.getRongyun_portrait_uri()).build();
                UserInfo info = new UserInfo(model.getRongyun_id(), model.getNickname(), Uri.parse(model.getRongyun_portrait_uri()));
                RongIM.getInstance().setCurrentUserInfo(info);
                RongIM.getInstance().startCustomerServiceChat(ServiceActivity.this, model.getCustomer_service(), getString(R.string.str_service_title), csInfo);

            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                dismissLoading();
            }
        });
    }

    private static class ViewHolder {
        TextView tv_title;
    }

    public class MyAdapter extends BaseAdapter {
        private LayoutInflater inflater;

        public MyAdapter(Context context) {
            this.inflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return iData.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return iData.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = inflater.inflate(R.layout.item_help_list, null);
                holder.tv_title = (TextView) convertView.findViewById(R.id.tv_title);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.tv_title.setText((String) iData.get(position).get("title"));
            return convertView;
        }
    }

    //帮助列表
    class ListenerHelpList implements IHttpPostListener {
        @Override
        public void onTimeOut() {

        }
        @Override
        public void responseSuccess(String result) {
            if (Ipost.isTimeOut(result)) {
                return;
            }
            Lg.d("帮助列表 result=" + result);
            if (null != result) {
                try {
                    JSONObject resultObject = new JSONObject(result);
                    int error = resultObject.getInt("error");
                    String message = "";
                    if (resultObject.has("error_msg") && error != 0) {
                        message = resultObject.getString("error_msg");
                        IToast.show(message);
                    }
                    if (error == 0) {
                        //成功
                        customer_service = resultObject.getString("customer_service");
                        email_service = resultObject.getString("customer_email");
                        JSONArray jsonArray = new JSONArray(resultObject.getString("data"));
                        iData = buildData(jsonArray);
                        MyAdapter adapter = new MyAdapter(ServiceActivity.this);
//                        //通过setAdapter而把数据绑定到ListView中
                        lv_help.setAdapter(adapter);
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    Lg.d(getClass() + ",接口解析异常：\n" + e.toString());
                }
            }
        }
    }

    public class RY extends GsonModel{
        private String error;
        private String code;
        private String userId;
        private String token;
        private String nickname;
        private String rongyun_id;
        private String rongyun_portrait_uri;
        private String
                customer_service;

        public String getError() {
            return error;
        }

        public void setError(String error) {
            this.error = error;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }

        public String getToken() {
            return token;
        }

        public void setToken(String token) {
            this.token = token;
        }

        public String getNickname() {
            return nickname;
        }

        public void setNickname(String nickname) {
            this.nickname = nickname;
        }

        public String getRongyun_id() {
            return rongyun_id;
        }

        public void setRongyun_id(String rongyun_id) {
            this.rongyun_id = rongyun_id;
        }

        public String getRongyun_portrait_uri() {
            return rongyun_portrait_uri;
        }

        public void setRongyun_portrait_uri(String rongyun_portrait_uri) {
            this.rongyun_portrait_uri = rongyun_portrait_uri;
        }

        public String getCustomer_service() {
            return customer_service;
        }

        public void setCustomer_service(String customer_service) {
            this.customer_service = customer_service;
        }
    }




    //帮助详情
    class ListenerHelpDetails implements IHttpPostListener {
        @Override
        public void onTimeOut() {

        }
        @Override
        public void responseSuccess(String result) {
            if (Ipost.isTimeOut(result)) {
                return;
            }
            Lg.d("帮助详情 result=" + result);
            if (null != result) {
                try {
                    JSONObject resultObject = new JSONObject(result);
                    int error = resultObject.getInt("error");
                    String message = "";
                    if (resultObject.has("error_msg") && error != 0) {
                        message = resultObject.getString("error_msg");
                        IToast.show(message);
                    }
                    if (error == 0) {
                        //成功
                        String data = resultObject.getString("data");
                        JSONObject jb = new JSONObject(data);

                        String title = jb.getString("title");
                        String content = jb.getString("content");
                        Intent intent = new Intent();
                        intent.setClass(ServiceActivity.this,HelpDetailsActivity.class);
                        intent.putExtra("title",title);
                        intent.putExtra("content",content);
                        startActivity(intent);
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    Lg.d(getClass() + ",接口解析异常：\n" + e.toString());
                }
            }
        }
    }

}
